﻿Public Class objMessageComposer
    Public Message As String
    Public ListReceive As ArrayList
End Class
Public Class clsMessageComposer
    Dim timCheck As Timer
    Dim SecondWait As Integer = 0
    Dim web As WebBrowser
    Dim step_action As String
    Dim ParseHTML As New clsParseHTML
    Dim is_send = False
    Dim TimeoutLogin As Integer = 30
    Dim objMessage As New objMessageComposer
    Dim Callback As Action(Of objMessageComposer)
    'TO DO check timeout
    Public Sub New()
        timCheck = New Timer
        timCheck.Enabled = True
        timCheck.Interval = 1000
        AddHandler timCheck.Tick, AddressOf timCheck_Tick
        web = New WebBrowser
        AddHandler web.DocumentCompleted, AddressOf web_DocumentCompleted
    End Sub

    Public Sub SendMessage(ByVal ListReceive As ArrayList, ByVal Message As String, Optional ByRef cback As Action(Of objMessageComposer) = Nothing)
        If is_send = False Then
            objMessage.Message = Message
            objMessage.ListReceive = ListReceive
            OpenSite(ListReceive)
            is_send = True
            If (cback IsNot Nothing) Then
                Callback = cback
            End If
        End If
    End Sub

    Private Sub OpenSite(ByVal ListReceive As ArrayList)
        step_action = "open"
        Dim strReceive As String = ""
        For Each item In ListReceive
            strReceive += "ids[" & item & "]=" & item & "&"
        Next
        Dim url As String = "https://m.facebook.com/messages/compose/?" & strReceive
        web.Navigate(url)
    End Sub

    Private Sub Timeout()

    End Sub

    Private Sub timCheck_Tick()

    End Sub

    Public Sub SendMessageSuccess(ByVal objMessage As objMessageComposer)
        If (Callback IsNot Nothing) Then
            Callback(objMessage)
        End If
        step_action = ""
        is_send = False
    End Sub

    Public Sub SendMessageFail()
        step_action = ""
        is_send = False
    End Sub

    Private Sub web_DocumentCompleted()
        If (frmMain.is_debug = True) Then
            frmDebug.web_debug_messagecomposer.Document.Write("<html><head><title></title><body>" & web.DocumentText & "</body></html>")
            frmDebug.txt_debug_messagecomposer.Text = web.DocumentText
        End If
        If step_action = "open" Then
            If (ParseHTML.CheckByName(web, "textarea", "body") = True) Then
                ParseHTML.SetByName(web, "textarea", "body", "innerText", objMessage.Message)
                ParseHTML.SetSubmitById(web, "composer_form")
                step_action = "send_message"
            End If
        ElseIf step_action = "send_message" Then
            If (ParseHTML.CheckByName(web, "textarea", "body") = True) Then
                SendMessageSuccess(objMessage)
            Else
                SendMessageFail()
            End If
        End If

    End Sub
End Class
